package org.budo.warehouse.logic.consumer.jdbc;

import java.util.List;
import java.util.concurrent.ExecutorService;

import org.budo.support.lang.util.ListUtil;
import org.budo.support.lang.util.StringUtil;
import org.budo.warehouse.logic.api.DataEntry;

/**
 * @author lmw
 */
public class MysqlDataConsumer extends JdbcDataConsumer {
//    private static final ExecutorService _EXECUTOR_SERVICE = new ThreadPoolExecutor(0, // corePoolSize
//            5, // maximumPoolSize
//            30L, TimeUnit.SECONDS, // keepAliveTime
//            new SynchronousQueue<Runnable>(), //
//            new ThreadPoolExecutor.CallerRunsPolicy()); // 线程池满时任务由主线程执行

    @Override
    public ExecutorService getExecutorService() {
        return null; // 所有实例共用同一个线程池
    }

    /**
     * 追加 ON DUPLICATE KEY UPDATE 逻辑
     */
    @Override
    public SqlUnit insertRow(DataEntry dataEntry, int rowIndex) {
        return this.insertOnDuplicateKeyUpdate(dataEntry, rowIndex);
    }

    @Override
    public SqlUnit updateRow(DataEntry dataEntry, int rowIndex) {
        return this.insertOnDuplicateKeyUpdate(dataEntry, rowIndex);
    }

    private SqlUnit insertOnDuplicateKeyUpdate(DataEntry dataEntry, int rowIndex) {
        SqlUnit insertRow = super.insertRow(dataEntry, rowIndex);
        List<Object> parameters = ListUtil.arrayToList(insertRow.getParameters());

        List<String> set = this.set(dataEntry, rowIndex, parameters);
        String sql = insertRow.getSql() + " ON DUPLICATE KEY UPDATE " + StringUtil.join(set, ", ");

        return new SqlUnit(sql, parameters.toArray());
    }
}